<?php

namespace mForge\Modules\Cache;

/**
 * APC (Alternative PHP Cache) wrapper.
 */
class ApcCacheHandler implements ICacheHandler
{
    /**
     * The cache expire time
     *
     * @var integer
     */
    protected $lifeTime;

    /**
     * Constructor.
     *
     * @param integer $expireTime
     * @return ApcCacheHandler
     */
    public function  __construct(array $options)
    {
        $defaults = array(
            'lifeTime' => 3600
        );

        $options = \mForge\Utility::arrayOverlay($defaults, $options);

        if (!extension_loaded('apc')) {
            throw new \RuntimeException('The APC PHP extension is not loaded.');
        }

        $this->lifeTime = $options['lifeTime'];

        return $this;
    }

    /**
     *
     * @param string $id
     * @return boolean
     */
    public function clean($id)
    {
        return apc_delete($id);
    }

    /**
     *
     *
     * @return boolean
     */
    public function cleanAll()
    {
        return apc_clear_cache('user');
    }

    /**
     *
     * @param string $id
     * @return mixed
     */
    public function load($id)
    {
        $value = apc_fetch($id, $result);
        if (!$result) {
            return null;
        }
        return $value;
    }

    /**
     *
     * @param string $id
     * @param string $value
     * @return boolean
     */
    public function save($id, $value)
    {
        return apc_store($id, $value, $this->lifeTime);
    }
}